﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;

namespace FloatingWindowTools.NormalFloatingWindow
{
    public partial class FloatingWindow : Form
    {
        public FloatingWindow(Window window)
        {
            InitializeComponent();
            this.MapinfoWindow = window;

            this.Load += new EventHandler(FloatingWindow_Load);
            this.Resize += new EventHandler(FloatingWindow_Resize);
            this.Closed += new EventHandler(FloatingWindow_Closed);
        }

        void FloatingWindow_Closed(object sender, EventArgs e)
        {
            this.MapinfoWindow.Close();
        }

        public Window MapinfoWindow { get; set; }

        void FloatingWindow_Resize(object sender, EventArgs e)
        {
            if (this.MapinfoWindow != null)
            {
                this.MapinfoWindow.UpdateSize(this.ReparentArea.Width, this.ReparentArea.Height);
            }
        }

        void FloatingWindow_Load(object sender, EventArgs e)
        {
            IntPtr mapinfoID = WinAPI.GetWindowThreadProcessId(this.MapinfoWindow.Handle, new IntPtr(0));
            IntPtr thread = new IntPtr(AppDomain.GetCurrentThreadId());

            // Attach our .net thread to the thread of the window we reparented.
            // This fixs issue (http://code.google.com/p/nathansmapinfoprojects/issues/detail?id=1) which was causing MapInfo's dialogs to draw incorrectly.
            WinAPI.AttachThreadInput(thread, mapinfoID, 1);

            this.MapinfoWindow.Parent = this.ReparentArea.Handle;
            this.MapinfoWindow.RemoveCaptionBar();
            this.MapinfoWindow.RemoveBorder();

            this.MapinfoWindow.Maximize();
            this.Text = this.MapinfoWindow.Title;

            int tempw = Convert.ToInt32(this.MapinfoWindow.Width);
            int temph = Convert.ToInt32(this.MapinfoWindow.Height);

            //Add one to the width to force a refresh.
            this.Width = tempw;
            this.Height = temph;
        }

        public enum WindowStyles : uint
        {
            WS_POPUP = 0x80000000
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams createParams = base.CreateParams;

                // Appear as a pop-up window
                int style = createParams.Style;
                createParams.Style = style + unchecked((int)WindowStyles.WS_POPUP);

                return createParams;
            }
        }
    }
}
